<style lang="scss" scoped>
  .content {
    margin-left: 0px;
    width: 100%;
    height: 100%;
    position: relative;
    .hy-search-bar {
      position: absolute;
      top: 10px;
      width: 100%;
      background: transparent;
      border: none;
    }
    .hy-tool-bar {
      position: absolute;
      background: transparent;
      z-index: 999;
      top: 90%;
      right: 45%;
      li {
        width: 32px;
        height: 32px;
        line-height: 32px;
        cursor: pointer;
        text-align: center;
        background: #5FADE3;
        float: left;
        margin-left: 10px;
        box-shadow: 2px 2px 3px #A7B0B6;
        border-radius: 4px;
        position: relative;
        .back {
          display: inline-block;
          transform: rotate(0.5turn);
          position: relative;
          top: -1px;
          left: -1px;
        }
        .play {
          display: inline-block;
          position: absolute;
          top: 2px;
          left: 10px;
        }
        .parse {
          display: inline-block;
          position: absolute;
          top: 2px;
          left: 7px;
        }
        &:active {
          box-shadow: inset 2px 2px 3px #A7B0B6;
        }
        &.noClick {
          margin-left: 0;
          background: rgb(253, 249, 249);
          border-radius: 0;
          width: 50px;
          color: #777777;
          cursor: default;
          user-select: none;
        }
        &.noClick:active {
          box-shadow: 2px 2px 3px #A7B0B6;
        }
        &.reduce {
          border-bottom-right-radius: 0;
          border-top-right-radius: 0;
        }
        &.add {
          margin-left: 0;
          border-bottom-left-radius: 0;
          border-top-left-radius: 0;
        }
      }
    }
  }
  .ivu-col-span-4{
    text-align: center;
    margin-top: 2px;
  }
</style>
<template>
  <div class="content map-content">
    <div id="pathMap" class="autoHeight"></div>
    <!--搜索条部分-->
    <div class="hy-search-bar">
      <div style="background-color: rgba(55,55,55,.1);height: 50px;min-width: 980px; line-height: 50px;">
        <div style="width: 980px;margin: 0 auto;">
          <div style="clear: both;height: 40px; float: left;width: 30%;">
            <i-input v-model="plateNum" readonly></i-input>
          </div>
          <div style="height: 40px;width: auto; float: left; margin-left: 30px">
            <DatePicker v-model="searchData.beginTime" type="datetime" :clearable="false" placeholder="选择日期和时间" style="width: 180px"></DatePicker>
          </div>
          <div style="height: 40px;width: auto; float: left; margin-left: 30px">
            <DatePicker v-model="searchData.endTime" type="datetime" :clearable="false" placeholder="选择日期和时间" style="width: 180px"></DatePicker>
          </div>
          <div style="height: 40px;width: auto; float: left; margin-left: 30px">
            <Button type="success" shape="circle" icon="ios-search" @click="search"
                    style="margin-left: 10px;margin-top: 3px">搜索
          </Button>
          </div>
        </div>
      </div>
    </div>
    <transition name="slide-up">
      <ul class="hy-tool-bar clearfix" style="padding-bottom: 10px;" v-show="toolShow">
        <Tooltip class="item" :content="content" placement="top-start">
          <li @click="channel()">
            <transition name="slide-down">
              <Icon v-if="!isPlay" type="play"></Icon>
              <Icon type="pause" v-else></Icon>
            </transition>
          </li>
        </Tooltip>
        <Tooltip content="停止" placement="top-start">
          <li @click="stop()">
            <Icon type="stop"></Icon>
          </li>
        </Tooltip>
        <Tooltip content="减少" placement="top-start">
          <li class="reduce" @click="reduce">
            <Icon type="minus"></Icon>
          </li>
        </Tooltip>
        <Tooltip content="速度" placement="top-start">
          <li class="noClick">x<span>{{speed}}</span>
          </li>
        </Tooltip>
        <Tooltip content="增加" placement="top-start">
          <li class="add" @click="add">
            <Icon type="plus-round"></Icon>
          </li>
        </Tooltip>
      </ul>
    </transition>
  </div>
</template>
<script>
  import BMap from 'BMap';
  import $ from 'jQuery';
  // import BMapLib from 'BMapLib';
  import service from './service';
  export default {
    data () {
      return {
        plateNum: null,
        currentVehicle: null,
        map: null,           // 地图
        isPlay: false,       // 是否播放
        isStart: true,       // 是否从开头开始播放
        marker: null,        // 标记
        toolShow: false,     // 按钮是否显示
        searchData: {
          vinOrDeviceCode: '',
          beginTime: '',
          endTime: ''
        },
        speed: '1.0',
        dongHua: [],
        luShu: {},
        mkrBus: null,
        label: null,
        allPoints: [], // 所有途径点
        currentPoint: 0 // 记录当前坐标点index
      };
    },
    mounted () {
      // 初始化时间
      this.searchData.beginTime = new Date(new Date().getTime() - (1000 * 60 * 60 * 24));
      this.searchData.endTime = new Date();
      this.init();
      // let gpsno = this.$route.query.gpsno;
      let plateNum = this.$route.query.plateNum;
      if (plateNum) {
        this.plateNum = plateNum;
        this.search();
      }
    },
    computed: {
      content () {
        if (this.isPlay) {
          return '暂停';
        } else {
          return '开始';
        }
      }
    },
    methods: {
      // 初始化地图
      init () {
        this.map = new BMap.Map('pathMap');
        this.map.centerAndZoom(new BMap.Point(103.388611, 35.563611), 6);
        this.map.enableScrollWheelZoom(true);     // 开启鼠标滚轮缩放
      },
      // 清除地图
      clearMap () {
        this.map.clearOverlays();
        this.speed = '1.0';        // 速度
        this.isPlay = false;       // 是否播放
      },
      getZoom (maxLng, minLng, maxLat, minLat) {
        let zoom = ['50', '100', '200', '500', '1000', '2000', '5000', '10000', '20000', '25000', '50000', '100000', '200000', '500000', '1000000', '2000000']; // 级别18到3。
        let pointA = new BMap.Point(maxLng, maxLat);  // 创建点坐标A
        let pointB = new BMap.Point(minLng, minLat);  // 创建点坐标B
        let distance = this.map.getDistance(pointA, pointB).toFixed(1);  // 获取两点距离,保留小数点后两位
        for (let i = 0, zoomLen = zoom.length; i < zoomLen; i++) {
          if (zoom[i] - distance > 0) {
            return 18 - i + 3;// 之所以会多3，是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。
          }
        }
      },
      setZoom (points) {
        if (points.length > 0) {
          let maxLng = points[0].lng;
          let minLng = points[0].lng;
          let maxLat = points[0].lat;
          let minLat = points[0].lat;
          let res;
          for (let i = points.length - 1; i >= 0; i--) {
            res = points[i];
            if (res.lng > maxLng) maxLng = res.lng;
            if (res.lng < minLng) minLng = res.lng;
            if (res.lat > maxLat) maxLat = res.lat;
            if (res.lat < minLat) minLat = res.lat;
          }
          ;
          let cenLng = (parseFloat(maxLng) + parseFloat(minLng)) / 2;
          let cenLat = (parseFloat(maxLat) + parseFloat(minLat)) / 2;
          let zoom = this.getZoom(maxLng, minLng, maxLat, minLat);
          this.map.centerAndZoom(new BMap.Point(cenLng, cenLat), zoom);
        } else {
          // 没有坐标，显示全中国
          this.map.centerAndZoom(new BMap.Point(103.388611, 35.563611), 5);
        }
      },
      // 初始化轨迹
      initPolyline (data) {
        this.allPoints = this.getPoints(data); // 格式化坐标
        this.createPolyLine(data); // 绘制线路
        // 添加站点、起点、终点marker
        // for (var j = 1; j < this.allPoints.length; j++) {
        //   let point = this.allPoints[j];
        //   if (j % 50 === 0) {
        //     this.addMarker('00', new BMap.Point(point.lng, point.lat));
        //   }
        // }
        this.move(); // 开始移动
        this.setZoom(this.getPoints(data)); // 缩放地图
      },
      createPolyLine (data) {
        // 用站点画出公交路线，参数：站点、线路颜色、线路宽度、透明度
        let arrPois = [];
        let lineColor = '';
        // 将后台读取到的GPS点信息，全部存储为百度的BMap.Point坐标点对象并用数组装起来
        // 循环遍历数组
        for (let i = 0; i < data.length - 1; i++) {
          arrPois.push({lng: data[i].lng, lat: data[i].lat});
          // 区间颜色
          if (data[i].speed < 30) {
            lineColor = 'blue';
            if (data[i + 1].speed < 30) {
              continue;
            } else {
              arrPois.push({lng: data[i + 1].lng, lat: data[i + 1].lat});
            }
          } else if (data[i].speed > 30 && data[i].speed < 60) {
            lineColor = 'green';
            if (data[i + 1].speed > 30 && data[i + 1].speed < 60) {
              continue;
            } else {
              arrPois.push({lng: data[i + 1].lng, lat: data[i + 1].lat});
            }
          } else if (data[i].speed > 60 && data[i].speed < 90) {
            lineColor = 'red';
            if (data[i + 1].speed > 60 && data[i + 1].speed < 90) {
              continue;
            } else {
              arrPois.push({lng: data[i + 1].lng, lat: data[i + 1].lat});
            }
          } else {
            lineColor = 'green';
            if (data[i + 1].speed > 60 && data[i + 1].speed < 90) {
              continue;
            } else {
              arrPois.push({lng: data[i + 1].lng, lat: data[i + 1].lat});
            }
          }
          let arrPoiss = this.getPoints(arrPois);
          // 创建线路
          var polyline = new BMap.Polyline(
            arrPoiss, // 所有的GPS坐标点
            {
              strokeColor: lineColor, // 线路颜色
              strokeWeight: 6, // 线路大小
              strokeOpacity: '0.8'
            });
          // 绘制线路
          this.map.addOverlay(polyline);
          arrPois.splice(0, arrPois.length); // 清空数组,如若不清空，会在原来基础上每次在重复的增加一边。这儿是让每两个点画线，否则第二次进来的时候就成四个数据了，第二个重复了一次
        }
      },
      search () {
        if (!this.searchData.beginTime || !this.searchData.endTime) {
          this.$Notice.warning({title: '请选择时间'});
          return;
        }
        let searchData = {
          from: this._hyTool.DateFormat(this.searchData.beginTime, 'yyyy-MM-dd hh:mm:ss'),
          to: this._hyTool.DateFormat(this.searchData.endTime, 'yyyy-MM-dd hh:mm:ss'),
          plate_num: this.plateNum
        };
        service.getHistoryLocation(searchData).then((data) => {
          this.dongHua = data.data;
          this.clearMap();
          this.isPlay = false;
          this.currentPoint = 0;
          this.initPolyline(this.dongHua);
          this.toolShow = true;
        });
      },
      channel () {
        this.isPlay = !this.isPlay;
        this.resetMkPoint(this.currentPoint);
      },
      // 获取data数据中的经纬度点并格式化点为BMap点
      getPoints (data) {
        let points = [];
        for (let i = 0; i < data.length; i++) {
          let x = data[i].lng;
          let y = data[i].lat;
          points[i] = new BMap.Point(x, y);
        }
        return points;
      },
      // 添加起点、终点、站点和公交标注
      addMarker (type, point) {
        if (type === '00') {
          // 创建图标 size定义Icon大小，anchor定义偏移量
          let icon00 = new BMap.Icon('/static/images/chaoshi.png', new BMap.Size(20, 20), {anchor: new BMap.Size(8, 8), imageSize: new BMap.Size(15, 15)});
          let mkr00 = new BMap.Marker(point, {icon: icon00});// 创建标注
          this.map.addOverlay(mkr00); // 将标注添加到地图上
          let label = new BMap.Label('超时时长5:00', {offset: new BMap.Size(0, -20)});
          label.setStyle({border: '1px solid #0033CC', borderRadius: '5px'});
          mkr00.setLabel(label);
          mkr00.setZIndex(-10000000);
        } else if (type === '01') {
          let icon01 = new BMap.Icon('http://api0.map.bdimg.com/images/blank.gif', new BMap.Size(32, 32), {anchor: new BMap.Size(16, 28)});
          let mkr01 = new BMap.Marker(point, {icon: icon01});
          this.map.addOverlay(mkr01);
        } else if (type === '02') {
          let icon02 = new BMap.Icon('http://api0.map.bdimg.com/images/blank.gif', new BMap.Size(32, 32), {anchor: new BMap.Size(16, 28)});
          let mkr02 = new BMap.Marker(point, {icon: icon02});
          this.map.addOverlay(mkr02);
        }
      },
      // 移动
      move () {
        let time = 200 - (50 * this.speed);
        // this.mkrBus.addEventListener('click', attribute);
        // function attribute () {
        //   alert('点击事件触发');
        // }
        let icon = new BMap.Icon('/static/images/car.png', new BMap.Size(50, 28), {anchor: new BMap.Size(20, 12)});// 声明icon
        this.mkrBus = new BMap.Marker(this.allPoints[0], {icon: icon}); // 声明标注
        this.map.addOverlay(this.mkrBus);
        let carInfo = {
          no: this.plateNum
        };
        this.label = new BMap.Label(this.createLabel(this.dongHua[0], carInfo), {offset: new BMap.Size(-95, -170)});
        this.label.setStyle({border: '1px solid #e0dcd5', borderRadius: '5px', background: '#000', opacity: 0.8});
        this.mkrBus.setLabel(this.label);
        $('#closeLabel').bind('click', () => {
          this.label.setStyle({display: 'none'});
        });
        let _this = this;
        setTimeout(function () {
          _this.resetMkPoint(0);
        }, time);
      },
      resetMkPoint (i) {
        if (!this.isPlay) return; // 停止播放
        let time = 200 - (50 * this.speed);
        this.label.setStyle({display: ''});
        this.mkrBus.setPosition(this.allPoints[i]);// 车辆位置
        let carInfo = {
          no: this.plateNum
        };
        this.label.setContent(this.createLabel(this.dongHua[i], carInfo));
        $('#closeLabel').bind('click', () => {
          this.label.setStyle({display: 'none'});
        });
        // this.mkrBus.setRotation(i); //车辆旋转角度
        if (i < this.allPoints.length - 1) {
          setTimeout(() => {
            i++;
            this.resetMkPoint(i);
          }, time);
        }
        this.currentPoint = i;
      },
      stop () {
        this.isPlay = false;
        this.currentPoint = 0;
      },
      // 增加速度
      add (ev) {
        if (this.speed >= 3.0) return;
        this.speed = (+this.speed + 0.5).toFixed(1);
      },
      // 减少速度
      reduce () {
        if (this.speed <= 0.5) return;
        this.speed = (+this.speed - 0.5).toFixed(1);
      },
      createLabel (positionInfo, carInfo) {
        return this._hyTool.createMapLable(positionInfo, carInfo);
      }
    },
    watch: {
    }
  };
</script>
